import { Form } from "antd";
import { Button, InputItem, List, Modal, TextareaItem, Toast, WhiteSpace, WingBlank } from "antd-mobile";
import { addon } from "pao-aop";
import { BaseReactElement, BaseReactElementControl, BaseReactElementState, reactControl } from "pao-aop-client";
import React from "react";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import { NTBraftEditor } from "src/business/components/buss-components/rich-text-editor";
import { request, setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { beforeUpload, ROUTE_PATH, getAppPermissonObject } from "src/projects/app/util-tool";
import { remote } from "src/projects/remote";
import { filterHTMLTag } from "../../home";
import { LOCAL_FUNCTION_LIST } from "src/business/mainForm/backstageManageMainForm";
/**
 * 组件：发布新闻状态
 */
export interface ChangeNewsViewState extends BaseReactElementState {
    // 新闻标题
    title?: any;
    // 新闻副标题
    subhead?: any;
    // 新闻描述
    description?: any;
    // 显示状态
    // showing_status_list?: any;
    // showing_status?: any;
    // showing_status_name?: any;
    // 文章内容
    content?: any;
    // 活动图片
    app_img_list?: any;
    // 金额
    author?: any;
    // 来源
    source?: any;
    // 是否已发送
    isSend?: boolean;
    // 新闻详情
    article_info?: any;
    // 是否作者
    isAuthor?: boolean;
}

/**
 * 组件：发布新闻
 * 发布新闻
 */

// const prompt = Modal.prompt;
const alert = Modal.alert;
export class ChangeNewsView extends BaseReactElement<ChangeNewsViewControl, ChangeNewsViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            title: '',
            subhead: '',
            // showing_status_list: ['首页', '置顶'],
            // showing_status: '',
            // showing_status_name: '',
            app_img_list: [],
            content: '',
            author: '',
            source: '',
            description: '',
            isSend: false,
            article_info: '',
            isAuthor: false,
        };
    }
    componentDidMount() {
        let user = IntelligentElderlyCareAppStorage.getCurrentUser();
        const AppPermission = JSON.parse(localStorage.getItem(LOCAL_FUNCTION_LIST)!);
        if (!user) {
            this.props.history!.push(ROUTE_PATH.login);
            return;
        }
        if (this.props.match!.params.key) {
            request(this, AppServiceUtility.article_list_service.get_news_list!({ 'id': this.props.match!.params.key, all: true }))
                .then((data: any) => {
                    // 有这篇文章或者作者或者权限者
                    if (data.result.length > 0 && data.result[0]['promulgator_id'] && data.result[0]['promulgator_id'] === user.id || AppPermission && getAppPermissonObject(AppPermission, '新闻管理', '编辑')) {
                        this.setState({
                            article_info: data.result[0],
                            title: data.result[0]['title'],
                            subhead: data.result[0]['subhead'],
                            app_img_list: data.result[0]['app_img_list'],
                            content: data.result[0]['content'],
                            author: data.result[0]['author'],
                            source: data.result[0]['source'],
                            description: data.result[0]['description'],
                            // showing_status: data.result[0]['showing_status'],
                            // showing_status_name: [data.result[0]['showing_status']],
                            isAuthor: true,
                        });
                    } else {
                        this.setState({
                            article_info: [],
                            isAuthor: false,
                        });
                    }
                });
        }
    }
    changeValue = (e: any, inputName: any) => {
        this.setState({
            [inputName]: e
        });
    }
    // changeStatus = (e: any) => {
    //     this.setState({
    //         showing_status: e[0],
    //         showing_status_name: e
    //     });
    // }
    Alert() {
        const { title, content } = this.state;
        if (title === '') {
            Toast.fail('请填写新闻标题！', 1);
            return;
        }
        // if (showing_status === '') {
        //     Toast.fail('请选择显示状态！', 1);
        //     return;
        // }
        if (filterHTMLTag(content).length > 1000) {
            Toast.fail('正文字数不能超过1000字！', 1);
            return;
        }
        if (content === '') {
            Toast.fail('请填写新闻内容！', 1);
            return;
        }
        alert('即将发布', '', [
            { text: '返回修改', onPress: () => console.log('cancel') },
            { text: '发布', onPress: () => this.NewsPush() },
        ]);
    }
    NewsPush() {
        const { title, subhead, description, content, author, source, app_img_list, isAuthor, article_info } = this.state;
        if (title === '') {
            Toast.fail('请填写新闻标题！', 1);
            return;
        }
        // if (showing_status === '') {
        //     Toast.fail('请选择显示状态！', 1);
        //     return;
        // }
        if (filterHTMLTag(content).length > 1000) {
            Toast.fail('正文字数不能超过1000字！', 1);
            return;
        }
        if (content === '') {
            Toast.fail('请填写新闻内容！', 1);
            return;
        }
        var param: any = {
            title,
            subhead,
            description,
            author,
            source,
            app_img_list: app_img_list || '',
            content: content || '',
        };
        if (isAuthor) {
            param['id'] = article_info.id;
        }
        Toast.loading('发布中...', 11, () => {
        });
        let st = setTimeout(
            () => {
                Toast.hide();
                Toast.fail('提交失败，请稍候再试', 3);
            },
            10000
        );
        request(this, AppServiceUtility.article_list_service.update_news!(param))
            .then((datas: any) => {
                if (datas === 'Success') {
                    clearTimeout(st);
                    Toast.hide();
                    Toast.success('发布成功', 3);
                    setTimeout(
                        () => {
                            this.props.history!.push(ROUTE_PATH.myRelease + '/资讯');
                        },
                        3000
                    );
                } else {
                    clearTimeout(st);
                    Toast.hide();
                    Toast.fail(`发布失败：${datas}`, 3);
                }
            })
            .catch(error => {
                clearTimeout(st);
                Toast.hide();
                Toast.fail(error.message);
            });
    }
    // 图片
    onAppImgListChange = (files: any, type: any, index: any) => {
        this.setState({
            app_img_list: files,
        });
    }

    // 文章内容
    onContentChange(e: any) {
        console.log(e);
        this.setState({
            content: e,
        });
    }

    render() {
        const { title, subhead, description, app_img_list, content, source, author, isAuthor } = this.state;

        const { getFieldDecorator } = this.props.form!;
        setMainFormTitle('资讯发布');
        // // 构建显示状态数据源
        // let showing_status_list_source: any[] = [];
        // showing_status_list!.map((item: any) => {
        //     showing_status_list_source.push({
        //         label: item,
        //         value: item,
        //     });
        // });
        // const
        //     borderBoth = {
        //         borderTop: '1px solid #ddd',
        //         borderBottom: '1px solid #ddd',
        //     };
        return (
            <div>
                <List renderHeader={() => '新闻标题'}>
                    <InputItem value={title || ''} clear={true} placeholder="新闻标题" onChange={(e) => this.changeValue(e, 'title')} />
                </List>
                <List renderHeader={() => '新闻副标题'}>
                    <InputItem value={subhead || ''} clear={true} placeholder="新闻副标题" onChange={(e) => this.changeValue(e, 'subhead')} />
                </List>
                {/* <List renderHeader={() => '显示状态'}>
                    <Picker data={showing_status_list_source} cols={1} value={showing_status_name} onChange={(e) => this.changeStatus(e)}>
                        <List.Item arrow="horizontal" style={borderBoth}>显示状态</List.Item>
                    </Picker>
                </List> */}
                <List renderHeader={() => '新闻描述'}>
                    <TextareaItem value={description || ''} placeholder="请输入新闻描述" rows={3} autoHeight={true} onChange={(e) => this.changeValue(e, 'description')} />
                </List>
                <List renderHeader={() => '新闻内容'}>
                    <NTBraftEditor value={content || ''} onChange={(e) => this.onContentChange(e)} remoteUrl={remote.upload_url} />
                </List>
                <List renderHeader={() => '新闻app图片列表'}>
                    {getFieldDecorator('app_img_list', {
                        initialValue: app_img_list || '',
                        rules: [{
                            required: false,
                        }],
                    })(
                        <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={(e) => this.changeValue(e, 'app_img_list')} />
                    )}
                    <WhiteSpace size="xs" />
                </List>
                <List renderHeader={() => '作者'}>
                    <InputItem value={author || ''} clear={true} placeholder="作者" onChange={(e) => this.changeValue(e, 'author')} />
                </List>
                <List renderHeader={() => '新闻来源'}>
                    <InputItem value={source || ''} clear={true} placeholder="新闻来源" onChange={(e) => this.changeValue(e, 'source')} />
                </List>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <WingBlank size="lg">
                    <Button type="primary" onClick={() => this.Alert()}>{isAuthor === true ? '保存修改' : '发布'}</Button>
                </WingBlank>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
            </div>
        );
    }
}

/**
 * 控件：发布新闻控制器
 * 发布新闻
 */
@addon('ChangeNewsView', '发布新闻', '发布新闻')
@reactControl(Form.create<any>()(ChangeNewsView), true)
export class ChangeNewsViewControl extends BaseReactElementControl {

}